package com.example.contentprovider

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.ContactsContract
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.contentprovider.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    private val contactList = ArrayList<String>()
    private lateinit var adapter: ArrayAdapter<String>


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        val binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // call phone
        binding.makeCallButton.setOnClickListener{
            val p = Manifest.permission.CALL_PHONE
            if( checkSelfPermission( p) != PackageManager.PERMISSION_GRANTED){
                requestPermissions(arrayOf(p), 1)
            }
            else{
                call()
            }
        }

        // read contact
        adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, contactList)
        binding.listView.adapter = adapter

        binding.readContactButton.setOnClickListener{
            val p = Manifest.permission.READ_CONTACTS
            if(checkSelfPermission(p) != PackageManager.PERMISSION_GRANTED){
                requestPermissions(arrayOf(p),2)
            }
            else{
                readContacts()
            }
        }
    }



    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
        deviceId: Int
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults, deviceId)

        when(requestCode)
        {
            1-> if ( grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                call()
            }else{
                Toast.makeText(this, "you denied permission call phone", Toast.LENGTH_SHORT).show()
            }

            2->if(grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                readContacts()
            }else{
                Toast.makeText(this, "you denied permission read contact", Toast.LENGTH_SHORT).show()
            }

        }
    }

    private fun call() {
        val intent = Intent(Intent.ACTION_CALL)
        intent.data = Uri.parse("tel:10086")
        startActivity(intent)
    }

    private fun readContacts() {
        contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null)?.apply {
            while(moveToNext()){
                val name = getString(getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))
                val number = getString(getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))
                contactList.add("$name\n$number")
            }

            adapter.notifyDataSetChanged()
            close()
        }

    }
}